package com.sikadwafastdaisfondturbo.pretloan.ui.launch

import android.annotation.SuppressLint
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import com.sikadwafastdaisfondturbo.pretloan.analysis.TestAnalysisInit
import com.sikadwafastdaisfondturbo.pretloan.databinding.ActivityLaunchBinding
import com.sikadwafastdaisfondturbo.pretloan.pro.ProActivity
import com.sikadwafastdaisfondturbo.pretloan.ui.credit.activity.CreditActivity
import com.sikadwafastdaisfondturbo.pretloan.ui.user.activity.UserLoginActivity
import com.sikadwafastdaisfondturbo.pretloan.utils.config.Configs
import com.sikadwafastdaisfondturbo.pretloan.utils.dialog.SikadwaUpdateDialog
import com.sikadwafastdaisfondturbo.pretloan.utils.event.EventType
import com.sikadwafastdaisfondturbo.pretloan.utils.helper.ActivityStackHelper
import com.sikadwafastdaisfondturbo.pretloan.utils.helper.SikadwaKefuConfigHelper
import com.sikadwafastdaisfondturbo.pretloan.utils.helper.SikadwaUpdateHelper
import com.sikadwafastdaisfondturbo.pretloan.utils.http.AppUrls
import com.sikadwafastdaisfondturbo.pretloan.utils.http.HttpDns
import com.sikadwafastdaisfondturbo.pretloan.utils.http.IHttpCallback
import org.json.JSONObject
import java.util.TimeZone

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/5/21 16:12
 * @Annotation：启动页
 */
@SuppressLint("CustomSplashScreen")
class LaunchActivity: ProActivity() {
    private lateinit var binding: ActivityLaunchBinding
    private var updateHelper: SikadwaUpdateHelper? = null
    private val updateLauncher = registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result ->
        if (result.resultCode == RESULT_OK) {
            // TODO: 更新成功，进入主界面
            onSikadwaJoinPage()
        } else {
            // 1、用户取消或失败，不处理，继续进入主界面
            // 2、如果需要强制，建议跳转应用商店，拦截进入主界面
            if (updateHelper == null) {
                onSikadwaJoinPage()
                return@registerForActivityResult
            }
            updateHelper?.haveNoUpdateCallback {
                onSikadwaJoinPage()
            }
        }
    }

    override fun getRootView(): View {
        binding = ActivityLaunchBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initView() {
        isNeedHideLoading = false
        //关闭所有页面
        ActivityStackHelper.finishAllActivity(LaunchActivity::class.java)
    }

    override fun initListener() {

    }

    override fun initData() {
        showLoading()
        // TODO: 坦桑时区需要通过域名获取到IP之后再调时区接口
        if (TimeZone.getDefault().id == "Africa/Dar_es_Salaam"){
            loadDNSIpResolver()
        } else {
            loadTimeZoneAction()
        }
        // TODO: 测试直接用域名访问
//        loadTimeZoneAction()
    }

    private fun onSikadwaJoinPage(){
        //已登录 - 进入主页
        if (Configs.getSPBoolean(Configs.SPKEY.SIKADWA_LOGIN)){
            //初始化analysis lib 赋值 用户id 和 token
            TestAnalysisInit.initAnalysisLibAtLoginSuccess()
            enterMainPage()
        } else {//进入登录页
            enterLoginPage()
        }
    }

    /**
     * 进入登录
     */
    fun enterLoginPage() {
        onIntent(UserLoginActivity::class.java)
        finish()
    }

    /**
     * 进入主页
     */
    fun enterMainPage() {
        //保存过时区 && 时区不相同 需要重新登录
        val saveZoneId = Configs.getSPString(Configs.SPKEY.SIKADWA_TIMEZONE_ID)
        if (saveZoneId.isNotEmpty() && saveZoneId != TimeZone.getDefault().id){
            enterLoginPage()
            return
        }
        onIntent(CreditActivity::class.java)
        finish()
    }

    /**
     * 时区获取成功
     */
    private fun showSikadwaTimeZoneSuccess(timeZoneString: String){
        var timeZone = ""
        var zoneCode = ""
        var zoneCountry = ""

        timeZoneString.split(",").apply {
            if (this.isNotEmpty()){
                timeZone = this[0].trim()
            }
            if (this.size >= 2){
                zoneCode = this[1].trim()
            }
            if (this.size >= 3){
                zoneCountry = this[2].trim()
            }
        }
        //保存转发地区
        Configs.saveSPString(Configs.SPKEY.SIKADWA_TIMEZONE,timeZone)
        //保存转发地区 区号
        Configs.saveSPString(Configs.SPKEY.SIKADWA_TIMEZONE_CODE,zoneCode)
        //保存国家标识
        Configs.saveSPString(Configs.SPKEY.SIKADWA_TIMEZONE_COUNTRY,zoneCountry)
        //初始化analysis lib 赋值 转发地区
        TestAnalysisInit.initAnalysisLibAtZoneSuccess()
        addEvent(EventType.PAGE.PAGE_LAUNCH_START,"")

        loadConfigAction()
    }

    /**
     * 获取客服配置成功
     */
    private fun showSikadwaConfigSuccess(){
        //保存转发地区
        val zoneCode = Configs.getSPString(Configs.SPKEY.SIKADWA_TIMEZONE_CODE)
        //保存转发地区 区号
        val zoneCountry = Configs.getSPString(Configs.SPKEY.SIKADWA_TIMEZONE_COUNTRY)
        //坦桑需要选择语言
        if (zoneCode == "255" || zoneCountry == "tanzania"){
            showSikadwaChooseLanguageDialog()
            return
        }
        checkSikadwaUpdate()
    }

    /**
     * 校验是否有更新
     */
    private fun checkSikadwaUpdate(){
        //强制更新
        if (SikadwaKefuConfigHelper.isSikadwaShowUpdateBreak()){
            showSikadwaAppUpdateDialog()
            return
        }
        onSikadwaJoinPage()
    }

    /**
     * 保存语言
     */
//    private fun showSikadwaSaveLanguage(languageName: String){
//        var appCurtLanguage = ""
//        val locale = AppCompatDelegate.getApplicationLocales()[0]
//        locale?.let {
//            appCurtLanguage = locale.language
//        }
//        AppCompatDelegate.setApplicationLocales(LocaleListCompat.forLanguageTags(languageName))
//        if (appCurtLanguage == languageName){//设置和当前应用语言相同的语言，应用不会重启
//            //检查更新
//            checkSikadwaUpdate()
//        }
//        //设置不同类型的语言后，应用会重启，重走时区接口
//    }

    /**
     * 选择语言
     */
    private fun showSikadwaChooseLanguageDialog(){
        val isChooseLanguage = Configs.getSPString(Configs.SPKEY.SIKADWA_LANGUAGE_CHOOSE).isNotEmpty()
        if (isChooseLanguage){
            //已选择过语言 - 直接检查更新
            checkSikadwaUpdate()
            return
        }
        showSikadwaProLangDialog("Launch page", isCancel = false, isCancelTouch = false,onCheckSuccess = {
            //检查更新
            checkSikadwaUpdate()
        })
    }

    /**
     * 版本更新Dialog
     */
    private fun showSikadwaAppUpdateDialog(){
        val versionUpdateDialog = SikadwaUpdateDialog(this,"Launch page",object : SikadwaUpdateDialog.IDialogCallback{
            override fun onUpdateNowClick() {
                try {
                    if (updateHelper == null){
                        updateHelper = SikadwaUpdateHelper(this@LaunchActivity, true, updateLauncher)
                    }
                    updateHelper?.checkVersionUpdate { onSikadwaJoinPage() }
                } catch (e: Exception) {
                    onSikadwaJoinPage()
                }
            }
        })
        versionUpdateDialog.show()
    }

    /**
     * 获取地区转发
     * Timezone
     */
    private fun loadTimeZoneAction(){
        val params = JSONObject().apply {
            put("p",Configs.AppName)
            put("tz", TimeZone.getDefault().id)
        }
        val httpUrl = AppUrls.APP_URL + AppUrls.URL.TIMEZONE
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val dataString = data.optString("data")
                showSikadwaTimeZoneSuccess(dataString)
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
            }

        })
    }

    /**
     * 获取APP配置信息
     */
    private fun loadConfigAction(){
        val params = JSONObject().apply {
            put("product",Configs.AppName)
            put("path",AppUrls.PATH.APP_INFO)
        }
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                hideLoading()
                val obj = data.optJSONObject("obj")
                //保存所有数据
                if (obj != null) {
//                    // 测试模拟版本更新
//                    val customize = obj.optJSONObject("customize")
//                    val customData = customize.optJSONObject("customData")
//                    var testVersion = customData.optJSONObject("release")
//                    if (Configs.getSPString(Configs.SPKEY.SIKADWA_LANGUAGE_CHOOSE) == "sw"){
//                        testVersion = customData.optJSONObject("release_sw")
//                    }
//                    testVersion.put("isMustUpdate",false)
//                    testVersion.put("versionCode","10")
//                    customData.put("release",testVersion)
                    Configs.saveSPString(Configs.SPKEY.SIKADWA_COMMON,obj.toString())
                }
                showSikadwaConfigSuccess()
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
                hideLoading()
            }
        })
    }

    /**
     * 坦桑地区要走DNS解析IP后再请求
     */
    private fun loadDNSIpResolver() {
        try {
            HttpDns().lookupSys(AppUrls.APP_URL) { ipAddr ->
                AppUrls.APP_URL = "https://$ipAddr"
                loadTimeZoneAction()
            }
        } catch (e: Exception){
            e.printStackTrace()
        }
    }

    override fun onResume() {
        super.onResume()
        try {
            updateHelper?.onResumeInProgress()
        } catch (e: Exception) {
            //
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        addEvent(EventType.PAGE.PAGE_LAUNCH_END,"")
    }
}